﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeEdu.MODEL;
using LeEdu.BLL;
using LeEdu.DAL;
using System.Net.Mail;
using System.Text;

namespace LeEdu.Web.Controllers
{
    public class AdminController : Controller
    {

        #region
        public ActionResult Showteacher()
        {
           ViewBag.list = userbll.getEntityList(p => true).Where(p => p.RoleId == 2).ToList();
           //List<string> list=new List<string>();
           //list.Add("Img.jpg");
           //ViewBag.ImageList=list; 
           return View();
        }
        #endregion
        #region 实例化BLL层
        /// <summary>
        /// 实例化UserInfoBLL
        /// </summary>
        UserInfoBLL userbll = new UserInfoBLL();
        #endregion
        #region 实例化上下文类
        /// <summary>
        /// 实例化上下文类
        /// </summary>
        DbContextEntity db = new DbContextEntity();
        #endregion
        #region 判断用户是否登陆
        /// <summary>
        /// 判断用户是否登陆
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            if (Session["User"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }
        #endregion
        #region 用户管理首页,用户信息分页+查询
        /// <summary>
        /// 用户管理首页,用户信息分页+查询
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <returns></returns>
        public ActionResult user(int PageIndex = 1)
        {
            if (Session["User"] != null)
            {
                UserInfoBLL bll = new UserInfoBLL();
                //  转换类型  user是string类型  UserInfo是opject类型
                UserInfo user = Session["User"] as UserInfo;
                List<UserInfo> list = new List<UserInfo>();
                int pageCount = 0;
                int total = 0;
                int pagesize = 2;
                string keywordType = Session["keywordType"] == null ? "" : Session["keywordType"].ToString();
                string str = Session["keyword"] == null ? "" : Session["keyword"].ToString();
                var a = Session["RoleId"];
                int roid = Session["RoleId"] == null ? 3 : Convert.ToInt32(Session["RoleId"]);

                if (str == "" && (roid == 0))
                {
                    list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => true), PageIndex, pagesize, out total, out pageCount);
                }
                else
                {
                    if (keywordType == "Uname")
                    {
                        list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => p.Uname.Contains(str) && (roid == 0 ? true : (roid == 3 ? p.RoleId == 0 : p.RoleId == roid))), PageIndex, pagesize, out total, out pageCount);//&& (RoleId == 3 ? true : p.RoleId == RoleId)
                    }
                    if (keywordType == "PhoneNum")
                    {

                        list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => p.PhoneNum.Contains(str) && (roid == 0 ? true : (roid == 3 ? p.RoleId == 0 : p.RoleId == roid))), PageIndex, pagesize, out total, out pageCount);
                    }
                    if (keywordType == "Email")
                    {
                        list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => p.Email.Contains(str) && (roid == 0 ? true : (roid == 3 ? p.RoleId == 0 : p.RoleId == roid))), PageIndex, pagesize, out total, out pageCount);
                    }
                    if (keywordType == "")
                    {
                        list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => (roid == 0 ? true : (roid == 0 ? true : (roid == 3 ? p.RoleId == 0 : p.RoleId == roid)))), PageIndex, pagesize, out total, out pageCount);
                    }
                }
                ViewBag.PageIndex = PageIndex;
                ViewBag.PageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(total) / 2));
                return View(list);
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }
        #endregion
        #region 教师管理首页,教师信息分页
        /// <summary>
        /// 教师管理首页,教师信息分页
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <returns></returns>
        public ActionResult teacher(int pageIndex = 1)
        {
            if (Session["User"] != null)
            {
                int pageSize = 2;
                List<UserInfo> lst = db.UserInfos.Where(p => p.RoleId == 2).ToList();
                int count = lst.Count();
                int pagecount = count / pageSize;
                if (count % pageSize > 1)
                {
                    pagecount += 1;
                }
                lst = lst.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageCount = pagecount;
                ViewBag.ss = lst;
                return View(lst);
            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }
        #endregion
        #region 模态框加载
        /// <summary>
        /// 模态框加载
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public ActionResult Show(int id)
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo u = bll.Search(id);
            ViewBag.lst = u;
            return View();
        }
        #endregion
        #region 教师状态更改
        /// <summary>
        /// 教师更改状态
        /// </summary>
        /// <param name="id">教师ID</param>
        /// <returns></returns>
        public ActionResult Ed(int id)
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo st = bll.Search(id);
            int i = 1;
            if (st.Tisornot == 1)
            {
                i = 0;
            }
            st.Tisornot = i;
            if (bll.Edit(st))
            {
                return RedirectToAction("teacher");
            }
            else
            {
                return RedirectToAction("teacher");
            }
        }
        #endregion
        #region 实名认证视图
        /// <summary>
        /// 实名认证视图
        /// </summary>
        /// <returns></returns>
        public ActionResult approvals()
        {
            List<UserInfo> list = userbll.getEntityList(p => true).Where(p =>(p.RoleId==2)&&( p.TeacherCheck == 0)).ToList();
            ViewBag.list = list;
            return View();
        }
        public ActionResult approvalss() {
        List<UserInfo> list = userbll.getEntityList(p => true).Where(p => (p.RoleId == 2) && (p.TeacherCheck == 1)).ToList();
            ViewBag.list = list;
            return View("approvals",list);
            }
        #endregion
        #region 单个用户详情
        /// <summary>
        /// 单个用户详情
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public ActionResult SingleUser(int id)
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo user = bll.Search(id);
            ViewBag.user = user;
            return View();
        }
        #endregion
        #region 用户的添加
        /// <summary>
        /// 用户的添加
        /// </summary>
        /// <returns></returns>
        public ActionResult Adduser()
        {
            //接收用户信息
            string email = Request["Email"];
            string UserName = Request["Uname"];
            string pwd = Request["Upwd"];
            string pwd2 = Request["Upwd2"];
            string Role = Request["RoleId"];

            UserInfo use = new UserInfo();
            use.Email = email;
            use.Uname = UserName;
            use.Upwd = pwd;
            use.UTime = DateTime.Now;

            if (Role == null)
            {
                use.RoleId = 1;
            }
            if (Role == "教师")
            {
                use.RoleId = 2;
            }

            UserInfoBLL bll = new UserInfoBLL();
            bool istrue = bll.AddEntity(use);
            if (istrue)
            {
                return RedirectToAction("User");
            }
            else
            {
                return Content("<script>alert('添加失败');location.href='Admin/User'</script>");
            }
        }
        #endregion
        #region 修改用户视图
        /// <summary>
        /// 修改用户视图
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public ActionResult EditUser(int id)
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo user = bll.Search(id);
            ViewBag.user = user;
            return View();
        }
        #endregion
        #region 修改用户信息
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditUser()
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo Newuse = new UserInfo();

            //接收用户信息
            int id = Convert.ToInt32(Request["UserInfoId"]);
            Newuse.UserInfoId = id;
            Newuse.Uname = Request["Uname"];
            Newuse.Sex = Convert.ToInt32(Request["Sex"]);
            Newuse.IDCard = Request["IDCard"];
            Newuse.PhoneNum = Request["PhoneNum"];
            Newuse.Company = Request["Company"];
            Newuse.Job = Request["Job"];
            Newuse.Post = Request["Post"];
            Newuse.Idiograph = Request["Idiograph"];
            Newuse.Self = Request["Self"];
            Newuse.PersonalHome = Request["PersonalHome"];
            Newuse.Microblog = Request["Microblog"];
            Newuse.QQ = Request["QQ"];
            Newuse.WeChat = Request["WeChat"];
            Newuse.Upwd = Request["Upwd"];
            Newuse.RoleId = Convert.ToInt32(Request["RoleId"]);
            Newuse.Tisornot = Convert.ToInt32(Request["Tisornot"]);
            Newuse.Email = Request["Email"];
            Newuse.Avatar = Request["Avatar"];
            Newuse.UTime = DateTime.Now;
            bool istrue = bll.Edit(Newuse);
            if (istrue)
            {
                return RedirectToAction("User");
            }
            else
            {
                return Content("<script>alert('添加失败');location.href='Admin/User'</script>");
            }
        }
        #endregion
        #region 登陆日志页面
        /// <summary>
        /// 登陆日志页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Login_Diary()
        {
            return View();
        }
        #endregion
        #region 后台用户页面查询
        /// <summary>
        /// 后台用户页面查询
        /// </summary>
        /// <param name="keywordType">用户角色</param>
        /// <param name="keyword">关键词</param>
        /// <returns></returns>
        public ActionResult SerchUser111(string keywordType, string keyword, int? RoleId)
        {
            Session["keywordType"] = keywordType;
            Session["keyword"] = keyword;
            Session["RoleId"] = RoleId;
            UserInfoBLL bll = new UserInfoBLL();
            List<UserInfo> list = new List<UserInfo>();

            int PageIndex = 1;
            int pageCount = 0;
            int total = 0;
            int pagesize = 2;

            if (string.IsNullOrEmpty(keyword) && (RoleId == 3))
            {
                Session["keyword"] = null;
                Session["RoleId"] = 3;
                list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => RoleId == 0 ? true : (RoleId == 3 ? p.RoleId == 0 : p.RoleId == RoleId)), PageIndex, pagesize, out total, out pageCount);
            }
            else
            {
                if (keywordType == "Uname")
                {
                    list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => (p.Uname.Contains(keyword)) && (RoleId == 0 ? true : (RoleId == 3 ? p.RoleId == 0 : p.RoleId == RoleId))), PageIndex, pagesize, out total, out pageCount);
                }
                if (keywordType == "PhoneNum")
                {
                    list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => p.PhoneNum.Contains(keyword) && (RoleId == 0 ? true : (RoleId == 3 ? p.RoleId == 0 : p.RoleId == RoleId))), PageIndex, pagesize, out total, out pageCount);
                }
                if (keywordType == "Email")
                {
                    list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => p.Email.Contains(keyword) && (RoleId == 0 ? true : (RoleId == 3 ? p.RoleId == 0 : p.RoleId == RoleId))), PageIndex, pagesize, out total, out pageCount);
                }
                if (keywordType == "")
                {
                    list = bll.getEntityPagging<int>((p => p.UserInfoId), (p => (RoleId == 0 ? true : (RoleId == 3 ? p.RoleId == 0 : p.RoleId == RoleId))), PageIndex, pagesize, out total, out pageCount);
                }
            }
            ViewBag.PageIndex = PageIndex;
            ViewBag.PageCount = pageCount;
            return View("user", list);
        }
        #endregion
        #region 修改用户角色页面
        /// <summary>
        /// 修改用户角色页面
        /// </summary>
        /// <param name="id">用户角色ID</param>
        /// <returns></returns>
        public ActionResult EditUserRole(int id)
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo user = bll.Search(id);
            ViewBag.user = user;
            return View();
        }
        #endregion
        #region 修改用户角色操作
        /// <summary>
        /// 修改用户角色操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditUserRole()
        {
            UserInfoBLL bll = new UserInfoBLL();
            UserInfo Newuse = new UserInfo();

            //接收用户角色信息
            Newuse.UserInfoId = Convert.ToInt32(Request["UserInfoId"]);
            Newuse.Uname = Request["Uname"];
            Newuse.Sex = Convert.ToInt32(Request["Sex"]);
            Newuse.IDCard = Request["IDCard"];
            Newuse.PhoneNum = Request["PhoneNum"];
            Newuse.Company = Request["Company"];
            Newuse.Job = Request["Job"];
            Newuse.Post = Request["Post"];
            Newuse.Idiograph = Request["Idiograph"];
            Newuse.Self = Request["Self"];
            Newuse.PersonalHome = Request["PersonalHome"];
            Newuse.Microblog = Request["Microblog"];
            Newuse.QQ = Request["QQ"];
            Newuse.WeChat = Request["WeChat"];
            Newuse.Upwd = Request["Upwd"];
            Newuse.RoleId = Convert.ToInt32(Request["RoleId"]);
            Newuse.Tisornot = Convert.ToInt32(Request["Tisornot"]);
            Newuse.Email = Request["Email"];
            Newuse.Avatar = Request["Avatar"];
            Newuse.UTime = DateTime.Now;
            Newuse.TeacherCheck = 1;
            bool istrue = bll.Edit(Newuse);
            if (istrue)
            {
                return RedirectToAction("User");
            }
            else
            {
                return Content("<script>alert('添加失败');location.href='Admin/User'</script>");
            }
        }
        #endregion
        #region 邮件发送公共方法
        /// <summary>
        /// 邮件发送公共类
        /// </summary>
        /// <param name="mailTo"></param>
        /// <param name="mailSubject"></param>
        /// <param name="mailContent"></param>
        /// <returns></returns>
        public static bool SendEmail(string mailTo, string mailSubject, string mailContent)
        {
            // 设置发送方的邮件信息,例如使用QQ的smtp
            string smtpServer = "smtp.qq.com"; //SMTP服务器
            string mailFrom = "1026823049@qq.com"; //登陆用户名
            string userPassword = "cherjgxjkjopbeda";//登陆密码-新版之后的QQ邮箱都是使用授权码,需要到邮箱-设置-账户里面找到-生成授权码-复制进来

            // 邮件服务设置
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;//由于使用了授权码必须设置该属性为true
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            smtpClient.Host = smtpServer; //指定SMTP服务器
            smtpClient.Credentials = new System.Net.NetworkCredential(mailFrom, userPassword);//用户名和密码

            // 发送邮件设置       
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(mailFrom, "乐知教育", System.Text.Encoding.UTF8);// 发送人
            mailMessage.To.Add(mailTo);//收件人
            mailMessage.Subject = mailSubject;//主题
            mailMessage.Body = mailContent;//内容
            mailMessage.BodyEncoding = Encoding.UTF8;//正文编码
            mailMessage.IsBodyHtml = true;//设置为HTML格式
            mailMessage.Priority = MailPriority.Low;//优先级

            try
            {
                smtpClient.Send(mailMessage); // 发送邮件
                return true;
            }
            catch (Exception)
            {
                return false;
                throw;
            }


        }
        #endregion
        #region 邮件发送
        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="user">邮件对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EmailSend(UserInfo user)
        {
            if (userbll.Edit(user))
            {

              if(  SendEmail(user.EmailAddress, "您成功通过教师资格审核", user.EmailContent))
              {
                  return Content("<script>alert('发送成功！！！');location.href='/Admin/teacher'</script>");
              }
              else
              {
                  return Content("<script>alert('发送失败！！！');location.href='/Admin/teacher'</script>");
              }
  
            }
            else
            {
                return Content("<script>alert('修改失败！！！');location.href='/Admin/teacher'</script>");
            }
        }
        #endregion
        #region 查找用户对象
        /// <summary>
        /// 查找用户对象
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public ActionResult Cz(int id)
        {
            UserInfo finduser = userbll.Search(id);
            ViewBag.finduser = finduser;
            return View();
        }
        #endregion
        #region 用户封禁
        /// <summary>
        /// 用户封禁
        /// </summary>
        /// <returns></returns>
        public int ChangSealState()
        {
            int id = Convert.ToInt32(Request["id"]);
            UserInfo user = userbll.Search(id);
            if (user.SealState != 1)
            {
                user.SealState = 1;
                userbll.Edit(user);
                return 1;
            }
            else
            {
                user.SealState = 0;
                userbll.Edit(user);
                return 0;
            }
        }
        #endregion
    }
}
